﻿Imports System.Xml
Imports System.IO
Imports System.Net

Public Class Form1
    Public AutoClose As String = "N"
    Dim LastReturn As String
    Dim CanClose As Boolean = False
#Region "Logs"
    Sub WriteStatus(Message As String)
        ToolStripStatusLabel1.Text = Message
    End Sub
    Sub WriteLogs(Message As String, StatValue As Integer)
        TextBox1.AppendText(Now & " : " & Message & vbCrLf)
        SaveLogs(Now & " : " & Message)
        ToolStripStatusLabel1.Text = Message
        ProgressStatusWLo(StatValue)
        If Message <> "Done" Then
            LastReturn = Message
        End If
    End Sub
    Sub SaveLogs(MessageLine)
        Try
            Dim FILE_NAME As String = My.Application.Info.DirectoryPath & "\APUlogs.txt"
            Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
            'For Each line In TextBox1.Lines
            '    objWriter.WriteLine(line)
            'Next
            objWriter.WriteLine(MessageLine)
            objWriter.Close()
            'WriteStatus("Done")
        Catch ex As Exception
            WriteStatus(ex.Message)
        End Try
    End Sub
    Sub ProgressStatus(val As Integer, Optional ByVal Msg As String = "")
        Try
            ProgressBar1.Value = val
            ProgressBar1.Refresh()
        Catch ex As Exception

        End Try
    End Sub
    Sub ProgressStatusWLo(val As Integer)
        Try
            ProgressBar1.Value = val
            ProgressBar1.Refresh()
        Catch ex As Exception

        End Try
    End Sub
#End Region
#Region "MainFunctions"
    Function FTPDoesDirectoryExist(directoryUrl As String, ftpuser As String, ftppassword As String) As Boolean
        Try
            ' Check that the target URL is properly formatted
            If Not directoryUrl.StartsWith("ftp://") Then directoryUrl = "ftp://" & directoryUrl

            ' Create a web request
            Dim request As FtpWebRequest = DirectCast(WebRequest.Create(directoryUrl), FtpWebRequest)
            request.Credentials = New NetworkCredential(ftpuser, ftppassword)
            request.Method = WebRequestMethods.Ftp.PrintWorkingDirectory
            request.Proxy = Nothing
            Dim response As FtpWebResponse = request.GetResponse()
            Using (response)
                Return True
            End Using
        Catch ex As Exception
            Return False
        End Try
    End Function
    Public Function ReadBinaryFile(strFilename As String) As Byte()
        Dim position As Integer = 0
        Dim bufferSize As Integer = 4096
        Dim bytes() As Byte
        ProgressBar1.Value = 0

        Using fsOpen As FileStream = New FileStream(strFilename, FileMode.Open)
            ReDim bytes((fsOpen.Length) - 1)
            Do
                If (position + bufferSize) > fsOpen.Length Then
                    fsOpen.Read(bytes, position, fsOpen.Length - position)
                    Exit Do
                Else
                    fsOpen.Read(bytes, position, bufferSize)
                End If
                ProgressStatus(((position / fsOpen.Length) * 100), "Analyzing ")
                Application.DoEvents()
                position += bufferSize
            Loop
        End Using

        Return bytes

    End Function
    Public Sub SaveBinaryFile(strFilename As String, bytesToWrite() As Byte)
        Dim position As Integer = 0
        Dim BufferSize As Integer = 4096
        ProgressBar1.Value = 0

        Using fsNew As FileStream = New FileStream(strFilename, FileMode.Create, FileAccess.Write)
            Do
                Dim intToCopy As Integer = Math.Min(BufferSize, bytesToWrite.Length - position)
                Dim buffer(intToCopy - 1) As Byte
                Array.Copy(bytesToWrite, position, buffer, 0, intToCopy)
                fsNew.Write(buffer, 0, buffer.Length)
                ProgressStatus(((position / bytesToWrite.Length) * 100), "Downloading ")
                Application.DoEvents()
                position += intToCopy
            Loop While position < bytesToWrite.Length
        End Using
    End Sub
    Function NetworkWithProgress(path As String, filename As String) As Boolean
        Try
            WriteStatus("Downloading " & filename)
            WriteLogs("Downloading " & filename, 0)
            SyncLock Me
                SaveBinaryFile(My.Application.Info.DirectoryPath & "\updates\" & filename, ReadBinaryFile(path & filename))
            End SyncLock
        Catch ex As Exception
            WriteStatus(ex.Message)
            WriteLogs(ex.Message, 0)
        End Try

        If File.Exists(My.Application.Info.DirectoryPath & "\updates\" & filename) Then

            Return True
        End If
        Return False
    End Function
    Function DownloadFTP(FileName As String, Username As String, Password As String) As Boolean
        Try
            Dim convert As String = FileName
            convert = convert.Replace("\", "/")
            MsgBox(convert)

            Dim clsRequest As System.Net.FtpWebRequest = _
            DirectCast(System.Net.WebRequest.Create(convert), System.Net.FtpWebRequest)
            clsRequest.Credentials = New System.Net.NetworkCredential(txtftpuser.Text, txtftppass.Text)
            clsRequest.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
            clsRequest.Proxy = Nothing
            'MsgBox(convert)
            Dim bFile() As Byte = System.IO.File.ReadAllBytes(FileName)

            ' download file...
            Dim clsStream As System.IO.Stream = clsRequest.GetRequestStream()
            SyncLock Me
                For offset As Integer = 0 To bFile.Length Step 1024
                    ProgressStatus(CType(offset * 100 / bFile.Length, Integer), "Downloading :")
                    Dim chunkSize As Integer = bFile.Length - offset
                    If chunkSize > 1024 Then chunkSize = 1024
                    clsStream.Write(bFile, offset, chunkSize)
                Next
                clsStream.Close()
                clsStream.Dispose()
            End SyncLock
            Return True
        Catch ex As Exception
            WriteStatus(ex.Message)
            WriteLogs(ex.Message, 0)
        End Try
        Return False
    End Function
    Function DownloadFTP2(FileName As String, Username As String, Password As String) As Boolean
        Try
            FileName = FileName.Replace(Chr(10), "")

            Dim buffer(1023) As Byte
            Dim bytesIn As Integer
            Dim output As IO.Stream
            SyncLock Me
                ' MsgBox(FileName)
                Dim setupRequest As System.Net.FtpWebRequest = DirectCast(WebRequest.Create(FileName), FtpWebRequest)

                'Dim setupRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create(FileName), System.Net.FtpWebRequest)
                setupRequest.Credentials = New System.Net.NetworkCredential(Username, Password)
                setupRequest.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
                setupRequest.Proxy = Nothing
                'setupRequest.UsePassive = True
                'setupRequest.KeepAlive = True

                ' Dim ftpResponse As System.Net.FtpWebResponse = DirectCast(setupRequest.GetResponse(), FtpWebResponse)
                Dim ftpResponse As System.Net.FtpWebResponse = setupRequest.GetResponse

                Dim ftpStream As Stream = ftpResponse.GetResponseStream()
                ' Dim ftpStream As Stream = setupRequest.GetRequestStream()

                Dim FilenameSplit As String() = FileName.Split("/")


                Dim OutputFile As String = My.Application.Info.DirectoryPath & "\updates\" & FilenameSplit(FilenameSplit.Length - 1)

                output = System.IO.File.Create(OutputFile)

                bytesIn = 1
                Do Until bytesIn < 1
                    bytesIn = ftpStream.Read(buffer, 0, 1024)
                    If bytesIn > 0 Then
                        output.Write(buffer, 0, bytesIn)
                        ProgressStatus(CType(bytesIn * 100 / buffer.Length, Integer), "Downloading :")
                        Application.DoEvents()
                    End If
                Loop
                MsgBox(OutputFile)
                output.Close()
                'ftpStream.Close()
                'ftpResponse.Close()
                setupRequest = Nothing
            End SyncLock
        Catch e As Exception
            WriteStatus(e.Message)
            WriteLogs(e.Message, 0)
        End Try

        Return False
    End Function
    Public Class FileInfoComparer
        Implements IComparer
        Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare

            Dim firstFile As New System.IO.FileInfo(x.ToString)
            Dim secondFile As New System.IO.FileInfo(y.ToString)

            Return DateTime.Compare(firstFile.LastWriteTime, secondFile.LastWriteTime)

        End Function
    End Class
    Function LatestFile(path) As String
        Try
            Dim fi As New System.IO.DirectoryInfo(path)
            Dim files = fi.GetFiles.ToList
            Dim first = (From file In files Select file Order By file.CreationTime Ascending).FirstOrDefault
            Dim last = (From file In files Select file Order By file.CreationTime Descending).FirstOrDefault
            Return first.FullName
        Catch ex As Exception
            WriteStatus(ex.Message)
            WriteLogs(ex.Message, 0)
            Return Nothing
        End Try
    End Function
#End Region

    Sub CheckUpdates()
        Dim DirectoryExist As Boolean = False
        Dim Method As String = "None"
        Dim HasFile As Boolean = False
        Dim Serverpath As String = txtsharepath.Text & lblGroup.Text
        Dim RolledOutItem As String = ""

        Try
Stage1:     'Check Server
            WriteStatus("Initializing Connectivity..")
            WriteLogs("Initializing Connectivity..", 0)


            WriteStatus("Checking Network Connectivity..")
            WriteLogs("Checking Network Connectivity..", 0)
            'GoTo FTP2
            If Directory.Exists(Serverpath) Then
                DirectoryExist = True
                Method = "Network"
                WriteStatus("Checking Network Connectivity OK")
                WriteLogs("Checking Network Connectivity OK", 99)
            Else
FTP:
                WriteStatus("Network Connectivity Failed")
                WriteLogs("Network Connectivity Failed", 0)

                WriteStatus("Checking Local FTP Connectivity..")
                WriteLogs("Checking Local FTP Connectivity..", 0)
                If FTPDoesDirectoryExist(txtftp.Text, txtftpuser.Text, txtftppass.Text) = True Then
                    DirectoryExist = True
                    Method = "FTP1"

                    WriteStatus("Local FTP Connectivity OK")
                    WriteLogs("Local FTP Connectivity OK", 99)

                Else
FTP2:
                    WriteStatus("Local FTP Connectivity Failed")
                    WriteLogs("Local FTP Connectivity Failed", 0)
                    WriteStatus("Checking Public FTP Connectivity..")
                    WriteLogs("Checking Public FTP Connectivity..", 0)
                    If FTPDoesDirectoryExist(txtftp2.Text, txtfrtuser2.Text, txtftppassword2.Text) = True Then
                        DirectoryExist = True
                        Method = "FTP2"
                        WriteStatus("Public FTP Connectivity OK")
                        WriteLogs("Public FTP Connectivity OK", 99)
                    Else
                        DirectoryExist = False
                    End If
                End If
            End If

            WriteStatus("Connectivity has been initialized")
            WriteLogs("Connectivity has been initialized", 99)

            If DirectoryExist = False Then
                WriteStatus("Failed to establish connection")
                WriteLogs("Failed to establish connection", 0)
                GoTo ExitCodes
            End If

Stage2:     'Check Latest
            Dim FilesInServer As String() = Nothing
            Dim FilesInLocal As String() = Directory.GetFiles(Serverpath)
            Dim FilesToDownload As New ArrayList
            WriteStatus("Collecting Information from Server..")
            WriteLogs("Collecting Information from Server..", 0)

            If Method = "Network" Then
                FilesInServer = Directory.GetFiles(Serverpath)
                For Each item In FilesInServer
                    Dim ItemInf As New FileInfo(item)
                    If File.Exists(My.Application.Info.DirectoryPath & "\updates\" & ItemInf.Name) = False Then
                        'MsgBox(My.Application.Info.DirectoryPath & "\updates\" & ItemInf.Name)
                        FilesToDownload.Add(ItemInf)
                        TextBox2.AppendText(ItemInf.Name & vbCrLf)
                    End If
                Next
            ElseIf Method = "FTP1" Then
                Dim reqFTP As FtpWebRequest = Nothing
                Dim response As FtpWebResponse
                reqFTP = DirectCast(WebRequest.Create(txtftp.Text & lblGroup.Text), FtpWebRequest)
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory
                reqFTP.Credentials = New NetworkCredential(txtftpuser.Text, txtftppass.Text)
                reqFTP.Proxy = Nothing
                response = DirectCast(reqFTP.GetResponse(), FtpWebResponse)
                Dim responseStream As Stream = response.GetResponseStream()
                Dim reader As New StreamReader(responseStream)

                FilesInServer = reader.ReadToEnd.TrimEnd.Split(vbCrLf)

                reader.Close()

                For Each item In FilesInServer
                    If File.Exists(My.Application.Info.DirectoryPath & "\updates\" & item) = False Then
                        'MsgBox(My.Application.Info.DirectoryPath & "\updates\" & ItemInf.Name)
                        Dim FTPItem As String
                        FTPItem = txtftp.Text & lblGroup.Text & item
                        FTPItem = FTPItem.Replace("\", "/")
                        FilesToDownload.Add(FTPItem)

                        TextBox2.AppendText(item & vbCrLf)
                    End If
                Next
            ElseIf Method = "FTP2" Then
                Dim reqFTP As FtpWebRequest = Nothing
                Dim response As FtpWebResponse
                reqFTP = DirectCast(WebRequest.Create(txtftp2.Text & lblGroup.Text), FtpWebRequest)
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory
                reqFTP.Credentials = New NetworkCredential(txtfrtuser2.Text, txtftppassword2.Text)
                reqFTP.Proxy = Nothing
                response = DirectCast(reqFTP.GetResponse(), FtpWebResponse)
                Dim responseStream As Stream = response.GetResponseStream()
                Dim reader As New StreamReader(responseStream)

                FilesInServer = reader.ReadToEnd.TrimEnd.Split(vbCrLf)

                reader.Close()

                For Each item In FilesInServer
                    If File.Exists(My.Application.Info.DirectoryPath & "\updates\" & item) = False Then
                        'MsgBox(My.Application.Info.DirectoryPath & "\updates\" & ItemInf.Name)
                        Dim FTPItem As String
                        FTPItem = txtftp2.Text & lblGroup.Text & item
                        FTPItem = FTPItem.Replace("\", "/")
                        FilesToDownload.Add(FTPItem)

                        TextBox2.AppendText(item & vbCrLf)
                    End If
                Next
            End If

            WriteStatus("Checking Information..")
            WriteLogs("Checking Information..", 0)

            If FilesToDownload.Count <= 0 Then
                WriteStatus("No Updates Found")
                WriteLogs("No Updates Found", 0)
                GoTo ExitCodes
            End If

Stage3:     'Download
            WriteStatus("Preparing to Download..")
            WriteLogs("Preparing to Download..", 99)
            If Method = "Network" Then
                For Each item As FileInfo In FilesToDownload
                    If NetworkWithProgress(Serverpath, item.Name) Then
                        'Success
                        ProgressStatus(0)
                        WriteStatus(item.Name & " Successfully Downloaded")
                        WriteLogs(item.Name & " Successfully Downloaded", 99)
                    End If
                Next
            ElseIf Method = "FTP1" Then
                For Each item As String In FilesToDownload
                    If DownloadFTP2(item, txtftpuser.Text, txtftppass.Text) Then
                        'ProgressStatus(0)
                        WriteStatus(item & " Successfully Downloaded")
                        WriteLogs(item & " Successfully Downloaded", 99)
                    End If
                Next
            ElseIf Method = "FTP2" Then
                For Each item As String In FilesToDownload
                    If DownloadFTP2(item, txtfrtuser2.Text, txtftppassword2.Text) Then
                        'ProgressStatus(0)
                        WriteStatus(item & " Successfully Downloaded")
                        WriteLogs(item & " Successfully Downloaded", 99)
                    End If
                Next
            End If

Stage4:     'Backup
            WriteStatus("Creating Restore Point..")
            WriteLogs("Creating Restore Point..", 0)
            SyncLock Me
                Process1.StartInfo.Arguments = "a -ep """ & My.Application.Info.DirectoryPath & "\backup\DATA_" & Now.ToString.Replace(":", "").Replace("/", "") & ".rar"" " & lblbootdrv.Text & "DATA"
                Process1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
                Process1.Start()
            End SyncLock
            Threading.Thread.Sleep(5000)
            WriteLogs("Creating Restore Point..", 50)
            SyncLock Me
                Process1.StartInfo.Arguments = "a -ep """ & My.Application.Info.DirectoryPath & "\backup\NEWDATA_" & Now.ToString.Replace(":", "").Replace("/", "") & ".rar"" " & lblbootdrv.Text & "NEWDATA"
                Process1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
                Process1.Start()
            End SyncLock
            Threading.Thread.Sleep(5000)
            WriteStatus("Restore Point Created")
            WriteLogs("Restore Point Created", 99)
Stage5:     'Extract
            WriteStatus("Checking Updates..")
            WriteLogs("Checking Updates..", 0)
            Dim TFile As New FileInfo(LatestFile(My.Application.Info.DirectoryPath & "\updates\"))
            RolledOutItem = TFile.Name
            WriteStatus("Applying Updates.." & TFile.Name)
            WriteLogs("Applying Updates.." & TFile.Name, 0)
            Dim CurrentPAth As String = Path.GetDirectoryName(TFile.FullName)
            WriteStatus("Extracting Updates to DATA..")
            WriteLogs("Extracting Updates to DATA..", 20)
            SyncLock Me
                Dim CommandLine As String = "x -y """ & TFile.FullName & """ """ & lblbootdrv.Text & "DATA\" & """"
                Dim startInfo As New ProcessStartInfo
                startInfo.FileName = Process1.StartInfo.FileName
                startInfo.Arguments = CommandLine
                startInfo.WindowStyle = ProcessWindowStyle.Hidden
                Process.Start(startInfo).WaitForExit()
            End SyncLock
            Threading.Thread.Sleep(9999)
            WriteStatus("Extracting Updates to NEWDATA..")
            WriteLogs("Extracting Updates to NEWDATA..", 70)
            SyncLock Me
                Dim CommandLine As String = "x -y """ & TFile.FullName & """ """ & lblbootdrv.Text & "NEWDATA\" & """"
                Dim startInfo As New ProcessStartInfo
                startInfo.FileName = Process1.StartInfo.FileName
                startInfo.Arguments = CommandLine
                startInfo.WindowStyle = ProcessWindowStyle.Hidden
                Process.Start(startInfo).WaitForExit()
            End SyncLock
            Threading.Thread.Sleep(9999)
            WriteStatus("Applying Updates..Success")
            WriteLogs("Applying Updates..Success", 99)
Stage6:     'Alert and Refresh Data
            WriteStatus("Refreshing Data")
            WriteLogs("Refreshing Data", 0)
            RefreshProcess.StartInfo.FileName = My.Application.Info.DirectoryPath & "\refreshdata.bat"
            'MsgBox(My.Application.Info.DirectoryPath & "\refreshdata.bat")
            RefreshProcess.Start()
            RefreshProcess.WaitForExit()
            LastReturn = "Success"
        Catch ex As Exception
            WriteStatus(ex.Message)
            WriteLogs(ex.Message, 0)
        End Try
ExitCodes:
        WriteLogs("Done", 0)
        WriteStatus("Done")
        CanClose = True
        Button1.Enabled = True

        'Signature
        'Method=(Auto/Manual); Store="";File="";

        Try
            Dim wcreq As HttpWebRequest
            wcreq = WebRequest.Create(lblHost.Text & "?Method=" & Method & "&Store=" & lblstore.Text & "&File=" & RolledOutItem & "&Return=" & LastReturn)
            wcreq.Proxy = WebProxy.GetDefaultProxy

            Dim objStream As Stream
            objStream = wcreq.GetResponse.GetResponseStream()
            Dim objReader As New StreamReader(objStream)
            Dim sLine As String = ""
            Dim i As Integer = 0

            Do While Not sLine Is Nothing
                i += 1
                sLine = objReader.ReadLine
                If Not sLine Is Nothing Then
                    Console.WriteLine("{0}:{1}", i, sLine)
                End If
            Loop
            WriteStatus(Console.ReadLine())
            WriteLogs(Console.ReadLine(), 0)
        Catch ex As Exception
            WriteStatus(ex.Message)
            WriteLogs(ex.Message, 0)
        End Try

        If AutoClose = "Y" Then
            End
        End If
    End Sub
    Dim Method As String = "Auto"
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try
            If File.Exists(My.Application.Info.DirectoryPath & "\APUlogs.txt") Then
                File.Delete(My.Application.Info.DirectoryPath & "\APUlogs.txt")
            End If

            If Directory.Exists(My.Application.Info.DirectoryPath & "\backup\") = False Then
                Directory.CreateDirectory(My.Application.Info.DirectoryPath & "\backup\")
            ElseIf Directory.Exists(My.Application.Info.DirectoryPath & "\updates\") = False Then
                Directory.CreateDirectory(My.Application.Info.DirectoryPath & "\updates\")
            End If
        Catch ex As Exception
            WriteStatus(ex.Message)
            WriteLogs(ex.Message, 0)
        End Try



        Try

            Me.Text = Me.Text & " v" & My.Application.Info.Version.ToString
            CheckForIllegalCrossThreadCalls = False
            'Read Settings from Xml
            Dim xr As XmlTextReader = New XmlTextReader(My.Application.Info.DirectoryPath & "\Settings.xml")
            Do While xr.Read()
                If xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "store" Then
                    lblstore.Text = xr.ReadElementString
                ElseIf xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "storeemail" Then
                    lblemail.Text = xr.ReadElementString
                ElseIf xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "sharepath" Then
                    txtsharepath.Text = xr.ReadElementString
                ElseIf xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "ftp" Then
                    txtftp.Text = xr.ReadElementString
                ElseIf xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "ftpuser" Then
                    txtftpuser.Text = xr.ReadElementString
                ElseIf xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "ftppass" Then
                    txtftppass.Text = xr.ReadElementString
                ElseIf xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "bootdrv" Then
                    lblbootdrv.Text = xr.ReadElementString
                ElseIf xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "ftp2" Then
                    txtftp2.Text = xr.ReadElementString
                ElseIf xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "ftpuser2" Then
                    txtfrtuser2.Text = xr.ReadElementString
                ElseIf xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "ftppass2" Then
                    txtftppassword2.Text = xr.ReadElementString
                ElseIf xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "StoreGroup" Then
                    lblGroup.Text = xr.ReadElementString
                ElseIf xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "Host" Then
                    lblHost.Text = xr.ReadElementString
                ElseIf xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "DateWillBeSend" Then
                    'Add Data Grid
                    'DataGridView1.Rows.Add(xr.ReadElementString)

                    'Get Date Today
                    Dim Today As String
                    If Now.Hour <= 10 Then
                        Today = Now.AddDays(-1).ToString("yyyyMMdd")
                    Else
                        Today = Now.ToString("yyyyMMdd")
                    End If
                Else
                    xr.Read()
                End If

            Loop
            'Read Arguments
            Dim CommandLineArgs As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Application.CommandLineArgs
            For i As Integer = 0 To CommandLineArgs.Count - 1
                'MessageBox.Show(CommandLineArgs(i))
                If CommandLineArgs(i).Contains("AutoClose") Then
                    AutoClose = CommandLineArgs(i + 1)
                ElseIf CommandLineArgs(i).Contains("help") Then
                    MsgBox("Arguments -AutoClose (Y/N) -ExtractWait (milliseconds)", vbInformation, "Help")
                End If
            Next
        Catch ex As Exception
            WriteStatus(ex.Message)
            WriteLogs(ex.Message, 0)
        End Try

        If t.IsAlive Then
            Button1.Enabled = False
        Else
            t.Start()
        End If

    End Sub
    Dim t As New Threading.Thread(AddressOf CheckUpdates)
    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
        WriteLogs(e.CloseReason.ToString, 0)
        WriteStatus(e.CloseReason.ToString)
        If CanClose = False Then
            e.Cancel = True
            Return
        End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If t.IsAlive = False Then
            Method = "Manual"
            t.Interrupt()
            t = New Threading.Thread(AddressOf CheckUpdates)
            t.Start()
        End If
    End Sub
End Class
